﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class Modules_Personal_ModTargetApply : System.Web.UI.Page
{
    IPerf_Personal_TargetHandler targetHandler = new Perf_Personal_TargetManage();
    IPerf_Personal_ModTargetHandler modTargetHandler = new Perf_Personal_ModTargetManage();
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_PostHandler postHandler = new Sys_PostManage();
    IPerf_Personal_TargetOwnerHandler toHandler = new Perf_Personal_TargetOwnerManage();
    IPerf_Flow_TraceHandler flowTraceHandler = new Perf_Flow_TraceManage();
    IPerf_Personal_ModTargetDtlHandler modTargetDtlHandler = new Perf_Personal_ModTargetDtlManage();
    IPerf_Personal_TargetTypeHandler ttHandler = new Perf_Personal_TargetTypeManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Id";
            ViewState["Accending"] = "desc";

            RefreshDataGridView();
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("302040"))
            {
                btnCreate.Visible = strPur.Contains("302042");
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    #region dataBind
    /// <summary>
    /// 初始化岗位信息表
    /// </summary>
    private void dataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            FillSearchDDL();

            SqlParameter[] parms2 = null;
            int counter = 0;
            DataTable dt = new DataTable();

            if (whereClause != string.Empty)
            {
                dt = modTargetHandler.GetPerf_Personal_ModTargetByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                whereClause = "1=1";
                ProcessParms(ref whereClause, ref parms2);
                counter = modTargetHandler.GetCounter(whereClause, parms2);
            }
            else
            {
                dt = modTargetHandler.GetPerf_Personal_ModTargetByPageList(ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                counter = modTargetHandler.GetCounter();
            }

            this.AspNetPager.RecordCount = counter;
            gvModTargetList.DataSource = dt;
            gvModTargetList.DataBind();

            ChangeUIVisibility(false);
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        // 读取本单位
        int userId = int.Parse(Session["CurrentUserID"].ToString());
        Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(userId);
        int orgId = userQuery.Org_ID;
        Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(orgId);
        if (orgQuery != null && (orgQuery.Type == (int)Enums.OrgType.ICU || orgQuery.Type == (int)Enums.OrgType.Office))
        {
            orgId = orgQuery.ID;
        }
        else if (orgQuery != null)
        {
            for (int i = 0; i < 10000; i++)         // 查找上级，直到上级是机关或工商所，此处用for是由于防止死循环的发生
            {
                orgQuery = orgHandler.GetSys_OrganizationQuery(orgQuery.Parent_ID);
                if (orgQuery == null)
                {
                    break;
                }
                else if (orgQuery.Type == (int)Enums.OrgType.ICU || orgQuery.Type == (int)Enums.OrgType.Office)
                {
                    orgId = orgQuery.ID;
                    break;
                }
            }
        }
        whereClause += " and Org_ID = @Org_ID";
        lstParm.Add(new SqlParameter("@Org_ID", orgId));

        if (ViewState["SearchPostID"] != null)
        {
            whereClause += " and Post_ID = @Post_ID";
            lstParm.Add(new SqlParameter("@Post_ID", int.Parse(ViewState["SearchPostID"].ToString())));
        }

        if (ViewState["SearchTOID"] != null)
        {
            whereClause += " and TargetOwner_ID = @TargetOwner_ID";
            lstParm.Add(new SqlParameter("@TargetOwner_ID", int.Parse(ViewState["SearchTOID"].ToString())));
        }

        if (ViewState["SearchStatus"] != null)
        {
            whereClause += " and Status = @Status";
            lstParm.Add(new SqlParameter("@Status", int.Parse(ViewState["SearchStatus"].ToString())));
        }

        parms = lstParm.ToArray();
    }

    private void FillSearchDDL()
    {
        FillSearchPost();
        FillSearchTO();
        FillSearchStatus();
    }

    private void FillSearchPost()
    {
        DataTable dt = postHandler.GetSys_PostList(" Status = @Status", new SqlParameter[] { new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid) }, " Name asc");
        ddlSearchPost.DataTextField = "Name";
        ddlSearchPost.DataValueField = "ID";
        ddlSearchPost.DataSource = dt;
        ddlSearchPost.DataBind();
        ddlSearchPost.Items.Insert(0, new ListItem("全部....", "0"));
    }


    private void FillSearchTO()
    {
        DataTable dt = toHandler.GetPerf_Personal_TargetOwnerList();
        ddlSearchTo.DataTextField = "Name";
        ddlSearchTo.DataValueField = "ID";
        ddlSearchTo.DataSource = dt;
        ddlSearchTo.DataBind();
        ddlSearchTo.Items.Insert(0, new ListItem("全部....", "0"));
    }

    private void FillSearchStatus()
    {
        DataTable dtStatus = new DataTable();
        dtStatus.Columns.Add("Value");
        dtStatus.Columns.Add("Name");
        DataRow drStatus;

        drStatus = dtStatus.NewRow();
        drStatus[0] = "-1";
        drStatus[1] = "全部....";
        dtStatus.Rows.Add(drStatus);

        drStatus = dtStatus.NewRow();
        drStatus[0] = "0";
        drStatus[1] = Enums.GetPersonalModTargetStatus(Enums.PersonalModTargetStatus.NewAssign);
        dtStatus.Rows.Add(drStatus);

        drStatus = dtStatus.NewRow();
        drStatus[0] = "1";
        drStatus[1] = Enums.GetPersonalModTargetStatus(Enums.PersonalModTargetStatus.OnFlowing);
        dtStatus.Rows.Add(drStatus);

        drStatus = dtStatus.NewRow();
        drStatus[0] = "2";
        drStatus[1] = Enums.GetPersonalModTargetStatus(Enums.PersonalModTargetStatus.Pass);
        dtStatus.Rows.Add(drStatus);

        drStatus = dtStatus.NewRow();
        drStatus[0] = "3";
        drStatus[1] = Enums.GetPersonalModTargetStatus(Enums.PersonalModTargetStatus.NotPass);
        dtStatus.Rows.Add(drStatus);

        ddlSearchStatus.DataSource = dtStatus;
        ddlSearchStatus.DataTextField = "Name";
        ddlSearchStatus.DataValueField = "Value";
        ddlSearchStatus.DataBind();
    }
    #endregion

    #region gvModTargetLIst

    protected void gvModTargetList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //
        if (e.CommandName == "view")
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString().Trim());
            try
            {
                targetDataBind(id);
            }
            catch
            {
                Jscript.AlertInAjax("操作失败!", UpdatePanel1);
            }
        }
    }

    protected void gvModTargetList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex > -1)
            {
                HtmlInputCheckBox chkSelected = (HtmlInputCheckBox)e.Row.FindControl("chkSelected");
                if (int.Parse(e.Row.Cells[7].Text.Trim()) == (int)Enums.PersonalModTargetStatus.NewAssign)
                    chkSelected.Visible = true;
                else
                    chkSelected.Visible = false;

                Sys_PostQuery postQuery = postHandler.GetSys_PostQuery(int.Parse(e.Row.Cells[2].Text));
                if (postQuery != null)
                    e.Row.Cells[2].Text = postQuery.Name;

                Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[3].Text));
                if (userQuery != null)
                    e.Row.Cells[3].Text = userQuery.Name;

                Perf_Personal_TargetOwnerQuery toQuery = toHandler.GetPerf_Personal_TargetOwnerQuery(int.Parse(e.Row.Cells[4].Text));
                if (toQuery != null)
                    e.Row.Cells[4].Text = toQuery.Name;

                userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[6].Text));
                if (userQuery != null)
                    e.Row.Cells[6].Text = userQuery.Name;

                Enums.PersonalModTargetStatus status = (Enums.PersonalModTargetStatus)int.Parse(e.Row.Cells[7].Text);
                e.Row.Cells[7].Text = Enums.GetPersonalModTargetStatus(status);
                ImageButton ibtnViewFlow = (ImageButton)e.Row.FindControl("ibtnViewFlow");
                ibtnViewFlow.Visible = status != Enums.PersonalModTargetStatus.NewAssign;
            }
        }
    }

    protected void gvModTargetList_Sorting(object sender, GridViewSortEventArgs e)
    {

        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshDataGridView();
    }

    #endregion

    #region Button

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (!ddlSearchPost.SelectedValue.Equals("0"))
            ViewState["SearchPostID"] = ddlSearchPost.SelectedValue;
        else
            ViewState["SearchPostID"] = null;

        if (!ddlSearchTo.SelectedValue.Equals("0"))
            ViewState["SearchTOID"] = ddlSearchTo.SelectedValue;
        else
            ViewState["SearchTOID"] = null;

        if (!ddlSearchStatus.SelectedValue.Equals("-1"))
            ViewState["SearchStatus"] = ddlSearchStatus.SelectedValue;
        else
            ViewState["SearchStatus"] = null;

        RefreshDataGridView();
    }

    protected void CreateButton_Click(object sender, EventArgs e)
    {
        if (Session["UserPurviews"] != null && Session["UserPurviews"].ToString().Contains("302042"))
        {
            List<string> ids = new List<string>();
            for (int i = 0; i < gvModTargetList.Rows.Count; i++)
            {
                if (gvModTargetList.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    HtmlInputCheckBox chkb = (HtmlInputCheckBox)gvModTargetList.Rows[i].FindControl("chkSelected");
                    if (chkb.Checked)
                        ids.Add(chkb.Value);
                }
            }
            if (ids.Count > 0)
            {
                int userId = int.Parse(Session["CurrentUserID"].ToString());
                foreach (string id in ids)
                {
                    int intId = int.Parse(id);
                    Perf_Personal_ModTargetQuery query = modTargetHandler.GetPerf_Personal_ModTargetQuery(intId);
                    if (query != null && query.Status == (int)Enums.PersonalModTargetStatus.NewAssign)
                    {
                        Perf_Flow_TraceQuery ftQuery = new Perf_Flow_TraceQuery();
                        ftQuery.Flow_ID = (int)Enums.PerfFlowIDs.PersonalFirstAssignApproval;
                        ftQuery.Business_ID = query.ID;
                        ftQuery.URL = Enums.Personal_FirstAssign_Flow_Form_URL;
                        ftQuery.Begin_Time = DateTime.Now;
                        ftQuery.Current_Step = 0;

                        int flowTraceId = 0;
                        flowTraceHandler.InsertPerf_Flow_Trace(ftQuery, ref flowTraceId);

                        // 更新状态和流程ID
                        if (flowTraceId != 0)
                        {
                            query.Status = (int)Enums.PersonalModTargetStatus.OnFlowing;
                            query.Flow_Trace_ID = flowTraceId;
                            query.User_ID = userId;
                            modTargetHandler.UpdatePerf_Personal_ModTarget(query);
                        }
                        else
                        {
                            Jscript.AlertInAjax("操作失败", UpdatePanel1);
                            return;
                        }
                    }
                }
                Jscript.AlertInAjax("操作成功", UpdatePanel1);
                RefreshDataGridView();
            }
            else
            {
                Jscript.AlertInAjax("请选择要呈批的记录", UpdatePanel1);
            }
        }
        else
        {
            Jscript.AlertInAjax("无此权限", UpdatePanel1);
        }
    }

    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        RefreshDataGridView();
    }

    #endregion

    private void ChangeUIVisibility(bool isTargetView)
    {
        searchContainer.Visible = !isTargetView;
        gvModTargetList.Visible = !isTargetView;
        AspNetPager.Visible = !isTargetView;

        divTargetTitle.Visible = isTargetView;
        gvTargetList.Visible = isTargetView;
    }

    private void RefreshDataGridView()
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }

    private void RefreshTargetList()
    {
        int modTargetId = int.Parse(hdnSelectedModTargetID.Value);
        targetDataBind(modTargetId);
    }

    protected void LBtnBack_Click(object sender, EventArgs e)
    {
        RefreshDataGridView();
    }

    protected void CreateTarget_Click(object sender, EventArgs e)
    {
        RefreshTargetList();
    }

    private void targetDataBind(int modTargetId)
    {
        try
        {
            Perf_Personal_ModTargetQuery query = modTargetHandler.GetPerf_Personal_ModTargetQuery(modTargetId);
            Sys_UserQuery targetUser = userHandler.GetSys_UserQuery(query.TargetUser_ID);
            lblTargetUserName.Text = targetUser.Name;
            hdnSelectedModTargetID.Value = modTargetId.ToString();

            string strPur = Session["UserPurviews"].ToString();
            if (query.Status != (int)Enums.PersonalModTargetStatus.NewAssign)
            {
                lbtnCreate.Visible = false;
                ViewState["CanEdit"] = false;
            }
            else
            {
                lbtnCreate.Visible = strPur.Contains("302041");
                ViewState["CanEdit"] = strPur.Contains("302041");
            }

            DataTable dt = new DataTable();

            dt = modTargetDtlHandler.GetPerf_Personal_ModTargetDtlList("ModTarget_ID = @ModTarget_ID", new SqlParameter[] { new SqlParameter("@ModTarget_ID", modTargetId) });
            
            gvTargetList.DataSource = dt;
            gvTargetList.DataBind();

            ChangeUIVisibility(true);
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    protected void gvTargetList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "del")
        {
            try
            {
                int id = Convert.ToInt32(e.CommandArgument.ToString().Trim());
                // 判断是否能够删除
                Perf_Personal_ModTargetDtlQuery dtlQuery = modTargetDtlHandler.GetPerf_Personal_ModTargetDtlQuery(id);

                if (dtlQuery != null)
                {
                    Perf_Personal_ModTargetQuery modTargetQuery = modTargetHandler.GetPerf_Personal_ModTargetQuery(dtlQuery.ModTarget_ID);
                    if (modTargetQuery.Status != (int)Enums.PersonalModTargetStatus.NewAssign)
                    {
                        Jscript.AlertInAjax("状态错误", UpdatePanel1);
                    }
                    else
                    {
                        modTargetDtlHandler.DeletePerf_Personal_ModTargetDtl(id);
                        Jscript.AlertInAjax("操作成功!", UpdatePanel1);
                    }
                    RefreshTargetList();
                }
            }
            catch
            {
                Jscript.AlertInAjax("操作失败!", UpdatePanel1);
            }
        }
    }

    protected void gvTargetList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton ibtnDel = (ImageButton)e.Row.FindControl("ibtnDelete");
            if (ViewState["CanEdit"] != null)
            {
                bool canEdit = (bool)ViewState["CanEdit"];
                if (!canEdit)
                {
                    ibtnDel.Visible = false;
                }
            }
            if (e.Row.RowIndex > -1)
            {
                Perf_Personal_TargetQuery targetQuery = targetHandler.GetPerf_Personal_TargetQuery(int.Parse(e.Row.Cells[1].Text));

                if (targetQuery != null)
                {
                    e.Row.Cells[1].Text = targetQuery.Code;
                    e.Row.Cells[2].Text = targetQuery.Name;

                    Perf_Personal_TargetTypeQuery ttQuery = ttHandler.GetPerf_Personal_TargetTypeQuery(targetQuery.TargetType_ID);
                    if (ttQuery != null)
                        e.Row.Cells[3].Text = ttQuery.Name;

                    e.Row.Cells[4].Text = targetQuery.Score.ToString();

                    Enums.YesNoStatus isRequired = (Enums.YesNoStatus)targetQuery.IsRequired;
                    e.Row.Cells[5].Text = Enums.GetYesNoStatus(isRequired);
                    if (isRequired == Enums.YesNoStatus.Yes)
                        ibtnDel.Visible = false;
                }

                Enums.PersonalModTargetType status = (Enums.PersonalModTargetType)int.Parse(e.Row.Cells[6].Text);
                e.Row.Cells[6].Text = Enums.GetPersonalModTargetType(status);
            }
        }
    }

    protected void gvTargetList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshTargetList();
    }
}
